﻿using Kingdee.BOS;
using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Deploy;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace LM.CB.K3Cloud.Plugin
{
    /// <summary>
    /// 生产订单服务插件
    /// </summary>
    /// <remarks>
    /// 功能：1、保存前获取工艺路线，填充工艺路线信息
    /// 创建人：lxl
    /// 创建日期：2024-10-14
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    [HotUpdate, Description("生产订单单据转换插件")]
    public class ProductConvertPlugin : AbstractConvertPlugIn
    {


        /// <summary>
        /// 最后触发：单据转换后事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterConvert(AfterConvertEventArgs e)
        {
            ExtendedDataEntity[] allBillDataObjs = e.Result.FindByEntityKey("FBillHead");
            //遍历单据转换之后的数据：多个生产订单
            foreach (ExtendedDataEntity data in allBillDataObjs)
            {
                ExtendedDataEntity myData = data;
                string fbilltype = (data["BillType"] as DynamicObject)?["id"].ToString() ?? "";//单据类型                                                                               //组织
                string FPrdOrgId = (data["PrdOrgId"] as DynamicObject)?["id"].ToString() ?? "0";//生产组织
                string F_DEV_Offset = Convert.ToString(data["F_DEV_Offset"]);//定制类型 1:定制，0：非定制
                DynamicObjectCollection fEntity = data["TreeEntity"] as DynamicObjectCollection;
                //获取单据体
                foreach (DynamicObject o2 in fEntity)
                {
                    #region 填充工艺路线字段
                    //物料
                    string FMaterialId = (o2["MaterialId"] as DynamicObject)?["id"].ToString() ?? "0";
                    //生产版本--上游
                    string fproductVisonSY = (o2["F_DEV_SCBB"] as DynamicObject)?["id"].ToString() ?? "0";
                    //工艺路线--上游
                    string F_DEV_GYLXSY = (o2["F_DEV_GYLX"] as DynamicObject)?["id"].ToString() ?? "0";
                    //bom--上游
                    string fbomSY = (o2["BomId"] as DynamicObject)?["id"].ToString() ?? "0";
                    //当选择了生产版本，则不从物料取数，直接从上游获取--不赋值2025-9-8 张亚妮提出修改
                    //bom
                    string fbom = "0"; string fproductVison = "0";
                    string F_DEV_GYLX1 = "0"; string F_DEV_GYLX = "0";
                    //1、首先根据物料获取工艺路线信息
                    string strSql = $"/*dialect*/select fid   from DEV_t_ProcessRoute where  F_DEV_CPBM={FMaterialId}";
                    DynamicObjectCollection getMtrlGarouObj1 = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                    if (getMtrlGarouObj1 != null && getMtrlGarouObj1.Count > 0)
                    {

                        F_DEV_GYLX1 = Convert.ToString(getMtrlGarouObj1[0]["fid"]);

                    }
                    else { F_DEV_GYLX1 = "0"; }
                    //2、根据物料获取生产版本\bom\工艺路线
                    strSql = $"/*dialect*/select fid,F_RDLV_BOM,F_RDLV_PROCESSROUTE  from RDLV_t_ProductVersion where F_RDLV_Product={FMaterialId}";
                    DynamicObjectCollection getMtrlGarouObj = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                    if (getMtrlGarouObj != null && getMtrlGarouObj.Count > 0)
                    {


                        //#工艺路线
                        F_DEV_GYLX = Convert.ToString(getMtrlGarouObj[0]["F_RDLV_PROCESSROUTE"]);
                        //生产版本
                        fproductVison = Convert.ToString(getMtrlGarouObj[0]["fid"]);
                        //bom
                        fbom = Convert.ToString(getMtrlGarouObj[0]["F_RDLV_BOM"]);

                    }
                    else //没有查到生产版本，物料上有工艺路线则赋值，bom和生产版本都设置成0
                    {
                        if (F_DEV_GYLX1 != "0" && F_DEV_GYLX != "")
                        {
                            F_DEV_GYLX = F_DEV_GYLX1;
                        }
                        else
                        {
                            F_DEV_GYLX = "0";
                        }
                        fproductVison = "0";
                        fbom = "0";
                    }
                    //如果上游选择了工艺路线，则用上游的
                    if (F_DEV_GYLXSY != "0")
                    {
                        F_DEV_GYLX = F_DEV_GYLXSY;
                    }
                    //如果上游选择了生产版本，则用上游的
                    if (fproductVisonSY != "0")
                    {
                        fproductVison = fproductVisonSY;
                    }
                    //如果上游选择了bom，则用上游的
                    if (fbomSY != "0")
                    {
                        fbom = fbomSY;
                    }
                    //如果是二次包装和利民化学的二次包装，则不赋值工艺路线
                    //#不考虑反工生产和二次包装二次人工包装
                    if (fbilltype == "b7dd912d4ef545578f0f5d1d08cb2602")
                    {
                        //#工艺路线
                        F_DEV_GYLX = "0";
                    }//化学的不考虑二次包装
                    else if (FPrdOrgId == "100083" && (fbilltype == "660a1e3f285fc4" || fbilltype == "668b460a5183a7"))
                    {
                        F_DEV_GYLX = "0";
                    }

                    //赋值工艺路线
                    BaseDataField fgylxFileld = e.TargetBusinessInfo.GetField("F_DEV_GYLX") as BaseDataField;
                    IViewService viewService0 = ServiceHelper.GetService<IViewService>();
                    DynamicObject[] fgylxObjs0 = viewService0.LoadFromCache(this.Context,
                        new object[] { F_DEV_GYLX },
                        fgylxFileld.RefFormDynamicObjectType);
                    o2["F_DEV_GYLX_id"] = F_DEV_GYLX;
                    o2["F_DEV_GYLX"] = fgylxObjs0.Count() > 0 ? fgylxObjs0[0] : null;

                    BaseDataField fscbbFileld = e.TargetBusinessInfo.GetField("F_DEV_SCBB") as BaseDataField;
                    IViewService viewService1 = ServiceHelper.GetService<IViewService>();
                    DynamicObject[] fscbbObjs0 = viewService1.LoadFromCache(this.Context,
                        new object[] { fproductVison },
                        fscbbFileld.RefFormDynamicObjectType);
                    o2["F_DEV_SCBB_id"] = fproductVison;
                    o2["F_DEV_SCBB"] = fscbbObjs0.Count() > 0 ? fscbbObjs0[0] : null;

                    //f赋值bom：如果上游订单没有选择bom，则赋值
                    if (fbom != "0" && F_DEV_Offset == "0")//查到了bom并且不是定制订单并且上游没有物料清单
                    {
                        BaseDataField fbomFileld = e.TargetBusinessInfo.GetField("fBomId") as BaseDataField;
                        IViewService viewService2 = ServiceHelper.GetService<IViewService>();
                        DynamicObject[] fbomObjs0 = viewService2.LoadFromCache(this.Context,
                            new object[] { fbom },
                            fbomFileld.RefFormDynamicObjectType);
                        o2["BomId_id"] = fbom;
                        o2["BomId"] = fbomObjs0.Count() > 0 ? fbomObjs0[0] : null;
                    }
                    #endregion
                    #region 填充工艺路线单据体
                    //子单据体对象
                    DynamicObjectCollection fSubEntity = o2["F_QLTK_SubEntity"] as DynamicObjectCollection;

                    strSql = $@"select a.fid,b.F_DEV_CBZX,b.F_DEV_FYXM,b.F_DEV_HYL,F_QLTK_ZYHD from DEV_t_ProcessRoute 
                                    a inner join DEV_t_ProcessRoute_E b on a.fid=b.fid  and a.fid ={F_DEV_GYLX}";
                    DynamicObjectCollection getResultObj = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                    if (getResultObj != null && getResultObj.Count > 0)
                    {
                        int rows = getResultObj.Count;
                        for (int findex = 0; findex < rows; findex++)
                        {
                            string fCenterid = Convert.ToString(getResultObj[findex]["F_DEV_CBZX"]);//成本中心
                            string fExpid = Convert.ToString(getResultObj[findex]["F_DEV_FYXM"]);//费用编码
                            string fhyl = Convert.ToString(getResultObj[findex]["F_DEV_HYL"]);//耗用量
                            string fzyhd = Convert.ToString(getResultObj[findex]["F_QLTK_ZYHD"]);//作业活动
                                                                                                 //给子单据体赋值
                            DynamicObject fSubEntityRow = new DynamicObject(fSubEntity.DynamicCollectionItemPropertyType);
                            //赋值成本中心
                            BaseDataField fCostFileld = e.TargetBusinessInfo.GetField("F_QLTK_CostCenter") as BaseDataField;
                            IViewService viewService4 = ServiceHelper.GetService<IViewService>();
                            DynamicObject[] fCostObjs0 = viewService4.LoadFromCache(this.Context,
                                new object[] { fCenterid },
                                fCostFileld.RefFormDynamicObjectType);
                            fSubEntityRow["F_QLTK_CostCenter_id"] = fCenterid;
                            fSubEntityRow["F_QLTK_CostCenter"] = fCostObjs0.Count() > 0 ? fCostObjs0[0] : null;

                            //赋值作业活动
                            BaseDataField fzyhdFileld = e.TargetBusinessInfo.GetField("F_QLTK_ZYHD") as BaseDataField;
                            IViewService viewService5 = ServiceHelper.GetService<IViewService>();
                            DynamicObject[] fzyhdObjs0 = viewService5.LoadFromCache(this.Context,
                                new object[] { fzyhd },
                                fzyhdFileld.RefFormDynamicObjectType);
                            fSubEntityRow["F_QLTK_ZYHD_id"] = fzyhd;
                            fSubEntityRow["F_QLTK_ZYHD"] = fzyhdObjs0.Count() > 0 ? fzyhdObjs0[0] : null;

                            //赋值费用项目
                            BaseDataField fexpFileld = e.TargetBusinessInfo.GetField("F_QLTK_ExpItem") as BaseDataField;
                            IViewService viewService6 = ServiceHelper.GetService<IViewService>();
                            DynamicObject[] fexpObjs0 = viewService6.LoadFromCache(this.Context,
                                new object[] { fExpid },
                                fexpFileld.RefFormDynamicObjectType);
                            fSubEntityRow["F_QLTK_ExpItem_id"] = fExpid;
                            fSubEntityRow["F_QLTK_ExpItem"] = fexpObjs0.Count() > 0 ? fexpObjs0[0] : null;

                            fSubEntityRow["F_QLTK_Qty"] = fhyl;
                            fSubEntityRow["Seq"] = findex + 1;
                            fSubEntity.Add(fSubEntityRow);

                        }
                    }
                    #endregion
                }
            }
        }
    }
}







